#include <stdio.h>   /* Standard input/output definitions */
#include <stdlib.h>  /* exit */
#include <string.h>  /* String function definitions */
#include <unistd.h>  /* UNIX standard function definitions */
#include <fcntl.h>   /* File control definitions */
#include <errno.h>   /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <ctype.h>   /* isxxx() */

#include "util.h"
#include "serial.h"

/* ------------------------------------------------------------------------

 cc -o 433 433.c

 Usage ./433 [option] ...

 -r, receiver (default)

 -t, transmitter

 -s BPS, bits per second, default 2400
 (300, 600, 1200, 1800, 2400, 4800, 9600, 19200)

 -m COUNT, test messages, default 1000

 ./433 -t -s4800 -m500 run as transmitter send 500 messages at 4800 bps
 ./433 -r -s4800       run as receiver (default), receive at 4800 bps

 -------------------------------------------------------------------------- */

int SerialConnection::openSerialPort(const char * device) {

	struct termios io;
	char buf[128];

	fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);

	if (fd == -1) {
		sprintf(buf, "openSerialPort %s error", device);
		perror(buf);
	} else {
		//io.c_cflag = B9600 | CS8 | CLOCAL | CREAD; //<Set baud rate
		io.c_cflag = B115200 | CS8 | CLOCAL | CREAD; //<Set baud rate
		//options.c_cflag = B9600 | CS8 | CLOCAL | CREAD; //<Set baud rate
		io.c_iflag = IGNPAR;
		io.c_oflag = 0;
		io.c_lflag = 0; //ICANON;
		tcflush(fd, TCIFLUSH);
		tcsetattr(fd, TCSANOW, &io);
	}
	return fd;
}


void SerialConnection:: tx_message(int fd, int mlen, const char * dat) {

	//wrote = write(fd, dat, mlen);
	FILE *file = fdopen(fd, "w");
	fprintf(file, "%s\r", dat);
	fflush(file);
	//printf("SENT %s\r\n", dat);

}



int SerialConnection:: rx_message(int fd, char * dat, int size) {

	int i = 0;
	i = read(fd, dat, sizeof(char) * size);
	return i;

}

void SerialConnection::close(int f){
	close(f);
}
